var select2;
var userForm;
$(function () {
    select2 = $('.select2').select2()
    var columns = [
        {
            field: 'ck',
            checkbox: true
        },
        {
            field: 'name',
            title: '姓名'
        },
        {
            field: 'loginName',
            title: '登录账号'
        },
        {
            field: 'mobile',
            title: '手机'
        },
        {
            field: 'loginFlag',
            title: '状态',
            formatter: function (value, row, index) {
                if (value == '0') {
                    return '<button type="button" class="btn btn-success  btn-xs" onclick="available(\'' + row.id + '\',\'' + value + '\')">正常</button>'
                } else {
                    return '<button type="button" class="btn btn-warning  btn-xs" onclick="available(\'' + row.id + '\',\'' + value + '\')">禁用</button>'
                }
            }
        },
        {
            field: 'createDate',
            title: '创建时间',
            // formatter: function (value, row, index) {
            //     return changeDateFormat("yyyy-MM-dd hh:mm:ss", new Date(value))
            // }
        }, {
            field: 'id',
            title: '操作',
            formatter: function (value, row, index) {
                return '<button type="button" class="btn btn-primary  btn-xs" onclick="update(\'' + value + '\')"><i class="fa fa-edit"></i> 修改</button>' +
                    '<button type="button" class="btn btn-danger  btn-xs" onclick="deletes(\'' + value + '\')" style="margin-left: 10px;"><i class="fa fa-trash-o"></i> 删除</button>';
            }
        }
    ]
    createBootstrapTable($("#table"), '/sys/sysUser/info', columns, true, 'toolbar', 'server')
    initTree('/sys/sysDept/zTreeNodes')
})

function openDeptTree() {
    openTree($("#zTree"))
}

function loadRole(res) {
    request('/sys/sysRole/findList', 0, null, function (data) {

        $("#typeck").empty()
        for (var i = 0; i < data.length; i++) {
            $("#typeck").append(
                '<input type="checkbox" name="role" class="minimal" value=' + data[i].id + '><span>' + data[i].name + ''
            )
        }
        if (res != undefined) {
            $.each($('input[name=role]'), function () {
                for (var j = 0; j < res.length; j++) {
                    if (res[j] == $(this).val()) {
                        $(this).prop("checked", true);
                    }
                }
            });
        }
    }, function (error) {
        layer.msg("角色信息加载异常！")
    })
}

function getPost(res) {
    var data = {
        status: 0
    }
    request('/sys/sysPost/findList', 0, data, function (data) {
        $("#postId").empty()
        for (var i = 0; i < data.length; i++) {
            $("#postId").append(
                ' <option value="' + data[i].id + '">' + data[i].postName + '</option>'
            )
        }
        if (res != undefined && res != null) {
            select2.val(res.id).trigger('change')
            select2.change()
        }
    }, function (error) {
        layer.msg("获取岗位信息异常！")
    })
}

function resetForm() {
    $("#userId").val('')
    $("#name").val('')
    $("#mobile").val('')
    $("#loginName").val('')
    $("#remarks").val('')
    $("#parentId").val('')
    $("#parentName").val('')
}

function add() {
    resetForm()
    userForm = layer.open({
        type: 1,
        area: (window.innerWidth>992)? "600px":"auto",
        title: '新增',
        shade: 0.6,
        maxmin: false,
        anim: 1,
        content: $("#user_form"),
        success: function (layero, index) {
            layer.iframeAuto(index);
        }
    });
    loadRole()
    getPost()
}

function save() {
    var id = $("#userId").val()
    var name = $("#name").val()
    var mobile = $("#mobile").val()
    var loginName = $("#loginName").val();
    var password = $("#password").val();
    var remarks = $("#remarks").val();
    var deptId = $("#parentId").val();
    var postId = $("#postId").val();

    if (loginName == '' || loginName == null) {
        layer.msg("请输入登录名！")
        return
    }
    if (id == null || id == '') {
        if (password == '' || password == null) {
            layer.msg("请输入密码！")
            return
        }
    }
    var ids = []
    $.each($('input[name=role]:checked'), function () {
        ids.push($(this).val())
    });

    if (ids.length < 1) {
        layer.msg("请至少分配一个角色    ！")
        return;
    }

    var data = {
        id: id,
        name: name,
        mobile: mobile,
        loginName: loginName,
        password: password,
        remarks: remarks,
        deptId: deptId,
        postId: postId,
        rids: ids.toString()
    }
    request('/sys/sysUser/save', 1, data, function (res) {
        if (res.code == 0) {
            layer.close(userForm)
            layer.msg(res.msg, {time: 1000}, function () {
                onLoads($("#href").val())
            })
        } else {
            layer.msg(res.msg, {time: 1000, icon: 5})
        }
    }, function (error) {
        layer.msg("系统异常！")
    })
}

function update(id) {
    resetForm()
    var data = {
        id: id
    }
    request('/sys/sysUser/update', 0, data, function (res) {
        $("#userId").val(res.data.data.id)
        $("#name").val(res.data.data.name)
        $("#mobile").val(res.data.data.mobile)
        $("#loginName").val(res.data.data.loginName)
        $("#remarks").val(res.data.data.remarks)
        $("#parentId").val(res.data.sysDept.id)
        $("#parentName").val(res.data.sysDept.deptName)
        loadRole(res.data.ids)
        getPost(res.data.sysPost)
    }, function (error) {
        layer.msg(error.msg, {icon: 5})
    })
    userForm = layer.open({
        type: 1,
        area: '600px',
        title: '修改',
        shade: 0.6,
        anim: 1,
        content: $("#user_form"),
        success: function (layero, index) {
            layer.iframeAuto(index);
        }
    });
}

function deletes(id) {
    var ids = [];
    if (id != undefined) {
        ids.push(id)
    } else {
        $.each($('tbody input:checkbox:checked'), function () {
            ids.push($(this).parents('tr').data('uniqueid'));
        });
    }
    if (ids.length < 1) {
        layer.msg("最少请选择一条数据！")
        return;
    }
    var data = {
        ids: ids.toString()
    }

    layer.confirm('确定删除吗？', {
        title:'提示',btn: ['取消', '确定'] //按钮
    }, function () {
        layer.close(layer.index)
    }, function () {
        request('/sys/sysUser/delete', 0, data, function (res) {
            if (res.code == 0) {
                layer.msg("删除成功", {time: 1000}, function () {
                    onLoads($("#href").val())
                })
            }else {
                layer.msg(res.msg, {time: 1000})
            }
        }, function (error) {
            layer.msg("系统异常！")
        })
    });
}

function available(id, val) {
    var data = {
        id: id
    }

    var tips;
    if (val == 0) {
        tips = '确定要禁用该用户吗？'
    } else {
        tips = '确定要启用该用户吗？'
    }

    layer.confirm(tips, {
        title:'提示',btn: ['取消', '确定'] //按钮
    }, function () {
        layer.close(layer.index)
    }, function () {
        request('/sys/sysUser/available', 0, data, function (res) {
            if (res.code == 0) {
                layer.msg(res.msg, {time: 1000}, function () {
                    onLoads($("#href").val())
                })
            } else {
                layer.msg(res.msg, {time: 1000})
            }

        }, function (error) {
            layer.msg("系统异常！")
        })
    });
}

// 查询
function searchForm(tableId,url ,FormId) {
    var data =serializeObject("searchForm");
    var opt = {
        url: '/sys/sysUser/info',
        silent: true,
        query:data
    };
    $("#table").bootstrapTable('refresh', opt);

}
//查询条件重置
function restForm(FormId) {
    var data =$("#searchForm")[0].reset();
}

